package Servlet;

import Dao.UserDao;
import Model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/UserRegisterServlet")

public class UserRegisterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取会话中的病人 ID
        Integer id = UserDao.selectNewId();
        User pat = new User(id, "123456");
        UserDao.insertUserNew(pat);

        // 使用 org.json.JSONObject 构建 JSON 对象
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", id); // 只添加 ID 到 JSON 对象

            // 设置响应内容类型为 JSON
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            // 将 JSON 数据写入响应
            try (PrintWriter out = response.getWriter()) {
                out.print(jsonObject.toString());
            }
        } catch (JSONException e) {
            // 处理 JSON 处理异常
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}